import OSS from 'ali-oss';

import {
	getStsRequest
} from '@/utils/api.js'

// 生成 UUID
function generateUUID() {
	return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
		var r = Math.random() * 16 | 0;
		var v = (c === 'x' ? r : (r & 0x3 | 0x8));
		return v.toString(16);
	});
}


const uploadFileUrl = 'https://shuidianbang.oss-cn-chengdu.aliyuncs.com/';

let fileUploadSuccessObj = {
		url: '',
		name: '',
		path: ''
	},
	fileUploadSuccessUrl = '';

function handleUploadFileApi(file) {
	// 文件后缀名
	if(!file.path){
		file.path = file.tempFilePath;
	}
	const index = file.path.lastIndexOf('.');
	const suffix = file.path.substring(index + 1);
	
	// 完整路径 分类/uuid.文件后缀
	const uuid = generateUUID();
	let fileName = 'Files/' + uuid + '.' + suffix;

	return new Promise((resolve, reject) => {
		getStsRequest(uni.getStorageSync('_token')).then(res => {
			if (res.code === 200) {
				let formOssData = {
					policy: res.data.param.policy,
					xOssSecurityToken: res.data.token,
					OSSAccessKeyId: res.data.param.OSSAccessKeyId,
					signature: res.data.param.signature,
					success_action_status: "200",
				};

				formOssData.key = fileName;
				handleUNIUploadFile(formOssData, file, fileName)
					.then((res) => {
						console.log('上传成功 fn:', res);
						resolve(res);
					})
					.catch((error) => {
						console.error('上传失败 fn:', error);
					});

				// return
			}
		});
	});
}

// 上传文件
function handleUNIUploadFile(formOssData, file, fileName) {
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: uploadFileUrl, // 你的服务器地址
			filePath: file.path,
			headers: {
				"Content-Type": "application/octet-stream",
				"x-oss-storage-class": "Standard",
				"x-oss-meta-custom-header": "custom-value"
			},
			name: 'file', // 服务器接收的字段名
			formData: formOssData,
			success: (res) => {
				if (res.statusCode === 200) {
					// 用objectkey和 endpoint可以拼接出url
					fileUploadSuccessUrl = uploadFileUrl + fileName;
					fileUploadSuccessObj = {
						url: fileUploadSuccessUrl,
						name: fileName,
						path: fileUploadSuccessUrl
					};
					res.fileUploadSuccessObj = fileUploadSuccessObj;
					resolve(res); // 上传成功，返回结果
				} else {
					reject(`上传失败: ${res.statusCode}`); // 上传失败，返回错误信息
					uni.showToast({
						icon: 'none',
						title: '上传失败，请重新上传！'
					});
				}
			},
			fail: function(err) {
				console.error('上传失败：', err);
				uni.showToast({
					icon: 'none',
					title: '上传失败，请重新上传！'
				});
			}
		});
	});
};

const tool_oss = {
	oss: {
		async upload(files, num = 1) {
			if (files.length === 0) {
				uni.showToast({
					icon: 'none',
					title: '请选择要上传的文件！'
				});
				return;
			}
			const uploadPromises = [];
			let ossUploadFile;
			for (let i = 0; i < files.length; i++) {
				await handleUploadFileApi(files[i]).then(res => {
					ossUploadFile = res;
					uploadPromises.push(res)
				});
			};
			
			if(num > 1){
				return uploadPromises;
			}else{
				return ossUploadFile;
			}
		}
	}
};

export default tool_oss;